package com;


import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class MainWindow extends JFrame {
    public MainWindow(){
        //设置窗体标题、大小、位置等
        this.setTitle("雷电战机");
        this.setSize(800,1000);
        this.setLocationRelativeTo(null);//居中
        this.setResizable(false);//禁止改变大小
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//关闭窗口退出游戏
        this.setVisible(true);//窗体显示

        //开启一个画画的线程，17毫秒画一次  1s 60帧
        new Thread(){
            //画画
            @Override
            public void run() {
                while (true){
                    repaint();//调用画的方法
                    try {
                        Thread.sleep(17);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //添加键盘的按键事件
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(status == 0){
                    //将按键的按下事件传递给before界面
                    before.keyPressed(e);
                }else if(status == 1){
                    play.keyPressed(e);
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                if(status == 0){
                    //将按键的弹起事件传递给before界面
                    before.keyReleased(e);
                }else if(status == 1){
                    play.keyReleased(e);
                }
            }
        });
    }
    //卡成PPT  失帧   fps    1s刷新数   1s  10帧  60帧 17毫秒
    //画
    Image image = null;

    //开始之前界面
    Before before = new Before(this);
    //游戏界面
    Play play = new Play();

    //定义界面状态  0：Before   1：paly
    int status = 0;
    @Override
    public void paint(Graphics g) {
        //窗体的画笔： Graphics g
        if(image == null){
            image = this.createImage(800,1000);
        }
        //拿到画布的笔
        Graphics graphics = image.getGraphics();

        //每一次拿到的都是“新”画布
        graphics.setColor(Color.BLACK);
        graphics.fillRect(0,0,800,1000);
        //再画
        this.draw(graphics);
        //将画布画到窗体
        g.drawImage(image,0,0,null);
    }

    public void draw(Graphics graphics){
        if(status == 0){
            //应该将画笔交给开始界面
            before.draw(graphics);
        }else if(status ==1){
            //应该将画笔交给游戏界面
            play.draw(graphics);
        }
    }
}
